/**
 * 监控大厅轮询 JS
 */
(function(){
	
	window.POLL = {};
	
	window.POLL.set = function(cfg){
		new polling(cfg);
	};
	
	function polling(cfg){
		this.cfg = cfg || {};
		
		this.errorNode = $(cfg.error_id);
		if(this.errorNode.length > 0){
			this.errorNode = this.errorNode[0];
		}
		
		// 检查是否配置了接口 URL
		if(typeof cfg.inter == "undefined" || typeof cfg.inter.url == "undefined"){
			this.errorNode && (this.errorNode.innerHTML = '请配置接口 URL');
		} else {
			this.flashObj = null;
			this.loadFlash();
		}		
	}
	/**
	 * 加载 Flash 文件
	 */
	polling.prototype.loadFlash = function (){
		var that = this;
		var cfg = this.cfg;
		swfobject.embedSWF(cfg.url, cfg.id, cfg.width, cfg.height, cfg.version, null, cfg.flashvars, cfg.params, cfg.attributes, function(el){
			if(el.success){
				that.flashObj = el.ref;
				that.loadFlashData({
					'url' : that.cfg.inter.url,
					'params' : that.cfg.inter.params,
					'timer' : that.cfg.inter.timer
				});
			}
		});
	};
	
	polling.prototype.loadFlashData = function (inter){
		var that = this;
		$.ajax({
			'url' : inter.url,
			'data' : inter.params || {},
			'cache' : false,
            dataType: "json",
			'success' : function(json){
                if(!json.flash) {console.log('no json.flash'); return;}
                var data = json.flash;
				data = eval("(" + data + ")");
                if(json.tabledata) {     //表格中的数据内容包括html代码
                    var table_obj = $("#tabledata");
                    if(table_obj) {
                        $("#tabledata").html(json.tabledata);
                     }
                }
				if(typeof data != "undefined" && typeof data.errno != "undefined" && data.errno != 1){
					that.errorNode && (that.errorNode.innerHTML = data.msg);
				} else {
                //console.dir(data);
					that.setFlashData(data);
					that.errorNode && (that.errorNode.innerHTML = '');
				}
			}
		});
		var timer = setTimeout(function(){
			that.loadFlashData(inter);
		}, inter.timer || 30000);
	};
	
	// 设置 Flash 数据
	polling.prototype.setFlashData = function(data){
		var that = this;
		if(!that.flashObj.setData){
			setTimeout(function(){
				that.setFlashData(data);
			}, 500);
		}else{
			that.flashObj.setData(data);
		}
	};
	
//	var cfg = $CONFIG || {};
	
	var node = $('#error');
	if(node.length > 0){
		node = node[0];
	}
	
	


})();
